<template>
    <div class="tinymce-editor">
        <editor v-model="myValue"
                :init="init"
                :disabled="disabled"
                @onClick="onClick"
                @onChange="handleEdit"
        >
        </editor>
    </div>
</template>
<script>
    import tinymce from 'tinymce/tinymce'
    import Editor from '@tinymce/tinymce-vue'
    import 'tinymce/themes/silver'
    // 编辑器插件plugins
    // 更多插件参考：https://www.tiny.cloud/docs/plugins/
    import 'tinymce/plugins/image'// 插入上传图片插件
    // import 'tinymce/plugins/media'// 插入视频插件
    import 'tinymce/plugins/table'// 插入表格插件
    import 'tinymce/plugins/lists'// 列表插件
    import 'tinymce/plugins/wordcount'// 字数统计插件
    import 'tinymce/plugins/paste'// 字数统计插件

    // import 'tinymce/plugins/emoticons'//插入表情插件
    export default {
        components: {
            Editor
        },
        props: {
            value: {
                type: String,
                default: ''
            },
            disabled: {
                type: Boolean,
                default: false
            },
            plugins: {
                type: [String, Array],
                default: 'lists image  table   paste '
            },
            toolbar: {
                type: [String, Array],
                default: 'undo redo | style_formats| alignleft aligncenter alignright | fontsizeselect |   formatselect | bold italic forecolor backcolor |  bullist numlist outdent indent | lists image  table  | removeformat'
            }
        },
        data() {
            let self = this
            return {
                init: {
                    language_url: '//yun.linkwinning.com/web/website/tinymce/langs/zh_CN.js',
                    language: 'zh_CN',
                    skin_url: '//yun.linkwinning.com/web/website/tinymce/skins/ui/oxide',
                    // skin_url: '/tinymce/skins/ui/oxide-dark',//暗色系
                    height: 600,
                    plugins: this.plugins,
                    toolbar: this.toolbar,
                    branding: false,
                    menubar: false,
                    image_uploadtab: true,
                    image_caption: true,  //图片标题
                    automatic_uploads: true,
                    object_resizing: false,
                    image_dimensions: false,
                    image_title: true,
                    image_description: false,
                    table_default_styles: {
                        width: '100%',
                        borderCollapse: 'collapse'
                    },
                    // 此处为图片上传处理函数，这个直接用了base64的图片形式上传图片，
                    // 如需ajax上传可参考https://www.tiny.cloud/docs/configure/file-image-upload/#images_upload_handler
                    images_upload_handler: (blobInfo, success, failure) => {
                        /*const img = 'data:image/jpeg;base64,' + blobInfo.base64()
                        success(img)*/
                        let formData = new FormData()
                        formData.append("file", blobInfo.blob(), blobInfo.filename()) //‘file’是後台接收文件名
                        let config = {
                            headers: {
                                "Content-Type": "multipart/form-data"
                            }
                        }
                        self.$upload(formData, null, config).then(res => {
                            const img = 'https://' + res.data.url + '/' + res.data.key
                                + "?"+ "imageMogr2/auto-orient/thumbnail/690x/format/jpg/blur/1x0/quality/75|watermark/1/image/aHR0cHM6Ly95dW4ubGlua3dpbm5pbmcuY29tL25hdkAyeC5wbmc=/dissolve/100/gravity/SouthEast/dx/24/dy/16|imageslim"
                            
                            success(img)
                        })
                    },
    
                    
                    
                    content_style: `
                            *                         { padding:0; margin:0; }
                            html, body                { height:100%; }
                            img                       { max-width:300px; display:block;height:auto; }
                            a                         { text-decoration: none; }
                            iframe                    { width: 100%; }
                            p                         { line-height:1.6; margin: 0px; }
                            table                     { word-wrap:break-word; word-break:break-all; max-width:100%; border:none; border-color:#999; }
                            .mce-object-iframe        { width:100%; box-sizing:border-box; margin:0; padding:0; }
                            ul,ol                     { list-style-position:inside; }
                          `,
                    
                    // CONFIG: Paste
                    paste_retain_style_properties: 'all',
                    paste_word_valid_elements: '*[*]',        // word需要它
                    paste_data_images: true,                  // 粘贴的同时能把内容里的图片自动上传，非常强力的功能
                    paste_convert_word_fake_lists: true,     // 插入word文档需要该属性
                    paste_webkit_styles: 'all',
                    paste_merge_formats: true,
                    nonbreaking_force_tab: false,
                    paste_auto_cleanup_on_paste: false,
    
                    powerpaste_word_import: 'propmt',// 参数可以是propmt, merge, clear，效果自行切换对比
                    powerpaste_html_import: 'propmt',// propmt, merge, clear
                    powerpaste_allow_local_images: true,
                    paste_data_images: true,
                    /*images_upload_handler: function (blobInfo, success, failure) {
                        // 这个函数主要处理word中的图片，并自动完成上传；
                        // ajaxUpload是自己定义的一个函数；在回调中，记得调用success函数，传入上传好的图片地址；
                        // blobInfo.blob() 得到图片的file对象；
                        let formData = new FormData()
                        formData.append("file", blobInfo.blob(), blobInfo.filename()) //‘file’是後台接收文件名
                        let config = {
                            headers: {
                                "Content-Type": "multipart/form-data"
                            }
                        }
                        self.$upload(formData, null, config).then(res => {
                            const img = 'https://' + res.data.url + '/' + res.data.key
                            success(img)
                        })
                    },*/
                    
                    imagetools_toolbar: 'rotateleft rotateright | flipv fliph | editimage imageoptions',
                    
                    // FontSelect
                    font_formats: `
            微软雅黑=微软雅黑;
            宋体=宋体;
            黑体=黑体;
            仿宋=仿宋;
            楷体=楷体;
            隶书=隶书;
            幼圆=幼圆;
            Andale Mono=andale mono,times;
            Arial=arial, helvetica,
            sans-serif;
            Arial Black=arial black, avant garde;
            Book Antiqua=book antiqua,palatino;
            Comic Sans MS=comic sans ms,sans-serif;
            Courier New=courier new,courier;
            Georgia=georgia,palatino;
            Helvetica=helvetica;
            Impact=impact,chicago;
            Symbol=symbol;
            Tahoma=tahoma,arial,helvetica,sans-serif;
            Terminal=terminal,monaco;
            Times New Roman=times new roman,times;
            Trebuchet MS=trebuchet ms,geneva;
            Verdana=verdana,geneva;
            Webdings=webdings;
            Wingdings=wingdings,zapf dingbats`,
                    
                    // CONFIG: StyleSelect
                    style_formats: [
                        {
                            title: '首行缩进',
                            block: 'p',
                            styles: {'text-indent': '2em'}
                        },
                        {
                            title: '行高',
                            items: [
                                {title: '1', styles: {'line-height': '1'}, inline: 'span'},
                                {title: '1.5', styles: {'line-height': '1.5'}, inline: 'span'},
                                {title: '2', styles: {'line-height': '2'}, inline: 'span'},
                                {title: '2.5', styles: {'line-height': '2.5'}, inline: 'span'},
                                {title: '3', styles: {'line-height': '3'}, inline: 'span'}
                            ]
                        },
                        
                        {
                            title: 'Image Left', selector: 'img', styles: {
                                'float': 'left',
                                'margin': '0 10px 0 10px'
                            }
                        },
                        {
                            title: 'Image Right', selector: 'img', styles: {
                                'float': 'right',
                                'margin': '0 10px 0 10px'
                            }
                        }
                    ],
                    
                },
                myValue: this.value,
                bbsArticlePicDOList: []
            }
        },
        mounted() {
            tinymce.init({})
        }
        ,
        methods: {
            // 添加相关的事件，可用的事件参照文档=> https://github.com/tinymce/tinymce-vue => All available events
            onClick() {
                this.bbsArticlePicDOList = this.getImgSrc(this.myValue)
                this.$emit('getBbsPicList', this.bbsArticlePicDOList)
            },
            // 可以添加一些自己的自定义事件，如清空内容
            clear() {
                this.myValue = ''
            },
            handleEdit() {
                this.bbsArticlePicDOList = this.getImgSrc(this.myValue)
                this.$emit('getHtml', this.myValue, this.bbsArticlePicDOList)
            },
            getImgSrc(htmlstr) {
                var reg = /<img.+?src=('|")?([^'"]+)('|")?(?:\s+|>)/gim
                var imgSrcArr = []
                var tem
                while (tem = reg.exec(htmlstr)) {
                    imgSrcArr.push({picUrl: tem[2]})
                }
                return imgSrcArr
            }
        }
        ,
        watch: {
            value(newValue) {
                this.myValue = newValue
            }
            ,
            myValue(newValue) {
                this.$emit('input', newValue)
            }
        }
    }

</script>

<style lang="less" scoped>
    .tinymce-editor {
        margin: 30px auto 0;
        width: 812px;
        position: relative;
        
        &::before {
            position: absolute;
            top: 18px;
            left: -20px;
            content: '';
            display: block;
            width: 4px;
            height: 4px;
            border-radius: 50%;
            background: rgba(250, 100, 0, 1);
        }
    }
    
    img {
        display: block !important;
    }
</style>
